<?php
namespace app\api\controller;
use think\Controller;
use think\Db;
use lib\UserCrypt;
class Collects extends Base{
	//收藏
	public function collectIn()
	{
		if(!empty(input("param.token"))){
            $token=input("param.token");
        }else{
            return json(['code' => 501, 'msg' => '令牌呢？']);
        }
		if(!empty(input("param.p_id"))){
			$data['p_id']=input("param.p_id");
		}else{
			return json(['code' => 502, 'msg' => '产品id']);
		}
        $uid=UserCrypt::do_mdecrypt($token);
        $isIn=Db::name('collects')->where('user_id',$uid)->where('p_id',$data['p_id'])->where('state',1)->find();
        if($isIn){
			return json(['code' => 503, 'msg' => '您已收藏过此产品']);
        }
		$data['user_id']=$uid;
		$data['state']=1;
		$data['time']=time();
		$data['uptime']=time();
		$res=Db::name('collects')->insert($data);
		if ($res) {
            return json(['code' => 200, 'msg' => '成功！']);
		}else{
            return json(['code' => 500, 'msg' => '失败！']);
		}
	}
	//我的收藏列表
	public function myCollects()
	{
		if(!empty(input("param.token"))){
            $token=input("param.token");
        }else{
            return json(['code' => 501, 'msg' => '令牌呢？']);
        }
        if(!empty(input("param.page"))){
            $page=input("param.page");
        }else{
            return json(['code' => 502, 'msg' => '当前分页数']);
        }
        $map = [
            ['a.state', '=', 1]
        ];
        $uid=UserCrypt::do_mdecrypt($token);
        array_push($map,['a.user_id','=',$uid]);
		$res=Db::name('collects')->alias('a')->join('product b', 'a.p_id = b.id','LEFT')->field('a.id,a.user_id,a.p_id,b.title,b.img')->where($map)->order('a.id desc')->limit(10*($page-1),10)->select();
		if ($res) {
			foreach ($res as $key => $value) {
                $res[$key]['combination']=Db::name('spec_combination')->where('p_id',$res[$key]['id'])->where('state',1)->order('id asc')->value('combination');
                $res[$key]['price']=Db::name('spec_combination')->where('p_id',$res[$key]['id'])->where('state',1)->order('id asc')->value('money');
            }
            return json(['code' => 200, 'msg' => '成功！','data'=>$res]);
		}else{
            return json(['code' => 500, 'msg' => '查无数据！']);
		}
	}
	//取消(删除)我的收藏
	public function cancelCollects()
	{
		if(!empty(input("param.token"))){
            $token=input("param.token");
        }else{
            return json(['code' => 501, 'msg' => '令牌呢？']);
        }
        if(!empty(input("param.id"))){
            $id=explode(',', input("param.id"));
        }else{
            return json(['code' => 502, 'msg' => 'id呢？']);
        }
        $res= Db::name('collects')->where(array('id'=>$id,'state'=>1))->update(['state'=>3]);
        if ($res) {
            return json(['code' => 200, 'msg' => '成功！']);
		}else{
            return json(['code' => 500, 'msg' => '失败！']);
		}
	}
}